package com.polaris.live.popup

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ScreenUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.databinding.PopupPreviewRichCharmBinding
import com.polaris.live.manager.DownFileManager
import com.polaris.live.resp.back_resp.RichCharmSizeBean
import com.polaris.live.resp.back_resp.UserRichCharmLevelRewardExplainVo
import com.polaris.live.resp.bean.decoration.CarAnimationLayersDto
import com.polaris.live.utils.AudioPlayProxy
import com.polaris.live.utils.DecorationUtils
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.viewscope.autoDisposeScope
import com.polaris.live.widget.PreViewEntryScreenItemView
import com.polaris.live.widget.avatar.FrameImageUtils
import com.polaris.live.widget.bubble.DownLoadFileUtil
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.libpag.PAGFile
import org.libpag.PAGImage
import org.libpag.PAGScaleMode
import org.libpag.PAGView
import java.io.File

/**
 * 壕魅等级页预览效果
 *
 * @author Created by 半仙 on 2024/9/19/019 10:33
 */
class PreviewRichCharmPopup(
    context: Context,
    private val mData: UserRichCharmLevelRewardExplainVo,
) : BottomPopupView(context) {

    private lateinit var mBinding: PopupPreviewRichCharmBinding

    override fun getImplLayoutId(): Int {
        return R.layout.popup_preview_rich_charm
    }

    private var isDismiss = false
    private var mPreViewEntryScreenItemView: PreViewEntryScreenItemView? = null
    override fun onCreate() {
        super.onCreate()
        mBinding = PopupPreviewRichCharmBinding.bind(popupImplView)
        mBinding.closeLl.setOnSingleClickListener {
            dismiss()
        }
        val effectUrl = mData.effectPhotoUrl
        if (effectUrl?.contains(PagConst.PAG) == true) {
            //空间背景
            if (mData.objectType == CommonConst.DressUp.PARTY_BACKGROUND || mData.objectType == CommonConst.DressUp.HOMEPAGE_BACKGROUND) {
                mBinding.pagView.setScaleMode(PAGScaleMode.Zoom)
                loadPag(effectUrl) {
                    showPag(it)
                }
            } else if (mData.objectType == CommonConst.DressUp.LIVE_BROADCAST_ENTRY) {//直播进场座驾
                DecorationUtils.getDecorationLiveCar(effectUrl)?.let { ud ->
                    if (ud.soundEffect != null) {
                        mBinding.loadingLl.visibility = VISIBLE
                        DownLoadFileUtil.downPagAndAudio(null, ud.url, ud.soundEffect) { p, a ->
                            mBinding.loadingLl.visibility = GONE
                            if (ud.url != p.first || ud.soundEffect != a.first) return@downPagAndAudio
                            val pag = p.second
                            val audio = a.second
                            if (pag != null && audio != null) {
                                showCarPagAndAudio(pag, a.first, ud.layers)
                            }
                        }

                    } else {
                        loadPag(ud.url) {
                            showPag(it)
                        }
                    }
                }
            } else if (mData.objectType == CommonConst.DressUp.LIVE_EFFECT) {//直播进场特效
                val url = effectUrl.substringBefore("?")
                loadPag(url) {
                    showPreViewEntryScreen(url)
                }
            } else if (mData.objectType == CommonConst.DressUp.AVATAR_FRAME) {//头像框
                mBinding.avFv.setFrameImage(FrameImageUtils.urlToFrameImageBean(effectUrl))
                mBinding.avHead.setImageUrl(UserManager.getUser().avatar, UserManager.getUserId())
            } else {
                val richCharmSize = mData.ext.let { JsonUtils.fromJson<RichCharmSizeBean>(it) }
                if (richCharmSize != null) {
                    if (richCharmSize.height != null && richCharmSize.width != null) {
                        val layoutParams = mBinding.pagView.layoutParams as ViewGroup.LayoutParams
                        layoutParams.height = (richCharmSize.height.toInt() / 3).autoDp
                        layoutParams.width = (richCharmSize.width.toInt() / 3).autoDp
                        mBinding.pagView.layoutParams = layoutParams
                    }
                }
                loadPag(effectUrl) {
                    showPag(it)
                }
            }
        } else {
            try {
                val richCharmSize = mData.ext.let { JsonUtils.fromJson<RichCharmSizeBean>(it) }
                if (richCharmSize != null) {
                    if (richCharmSize.height != null && richCharmSize.width != null) {
                        val layoutParams = mBinding.ivImage.layoutParams as ViewGroup.LayoutParams
                        layoutParams.height = (richCharmSize.height.toInt() / 3).autoDp
                        layoutParams.width = (richCharmSize.width.toInt() / 3).autoDp
                        mBinding.ivImage.layoutParams = layoutParams
                    }
                }
            } catch (e: Exception) {

            }
            mBinding.ivImage.visibility = VISIBLE
            Glide.with(context)
                .load(ImageUtils.imgPath(mData.photoUrl))
                .into(mBinding.ivImage)
        }
    }

    private fun showPreViewEntryScreen(mUrl: String) {
        mPreViewEntryScreenItemView = PreViewEntryScreenItemView(context).apply {
            setData(mUrl)
            setOnEntryScreenAnimationEnd {
                if (!isDismiss) {
                    mBinding.root.post {
                        mPreViewEntryScreenItemView?.startAnimation()
                    }
                }
            }
            layoutParams =
                ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                    .apply {
                        topMargin = ScreenUtils.getScreenHeight() / 2
                    }

        }
        mBinding.root.addView(mPreViewEntryScreenItemView)
        mPreViewEntryScreenItemView?.startAnimation()
    }

    private fun showCarPagAndAudio(path: String, audio: String, layers: CarAnimationLayersDto?) {
        mBinding.pagView.visibility = View.VISIBLE
        val pagFile = PAGFile.Load(path)
        if (layers != null) {
            val user = UserManager.getUser()
            mBinding.pagView.autoDisposeScope.launch {
                val texts = layers.text
                if (texts?.isNotEmpty() == true) {
                    texts.forEach {
                        user.nickname?.let { name ->
                            val showText = if (name.length > 8) {
                                name.substring(0, 8)
                            } else {
                                name
                            }
                            val textData = pagFile.getTextData(it.index)
                            textData.text = showText
                            pagFile.replaceText(it.index, textData)
                        }

                    }
                }
                val images = layers.image
                if (images?.isNotEmpty() == true) {
                    images.forEach {
                        user.avatar?.let { avatar ->
                            val loadNetImageBitmap = ImageUtils.loadNetImageBitmap(context, avatar)
                            val pagImage = PAGImage.FromBitmap(loadNetImageBitmap)
                            pagFile.replaceImage(it.index, pagImage)

                        }

                    }
                }
            }
        }
        mBinding.pagView.apply {
            composition = pagFile
            setRepeatCount(-1)
            addListener(object : PAGView.PAGViewListener {
                override fun onAnimationStart(p0: PAGView?) {
                }

                override fun onAnimationEnd(p0: PAGView?) {
                    AudioPlayProxy.instance().recycle()
                }

                override fun onAnimationCancel(p0: PAGView?) {
                }

                override fun onAnimationRepeat(p0: PAGView?) {
                    AudioPlayProxy.instance().stopPlay()
                    AudioPlayProxy.instance().playSound()
                }

                override fun onAnimationUpdate(p0: PAGView?) {
                }

            })
            if (!isPlaying) {
                play()
            }
        }
        audio.let {
            AudioPlayProxy.instance().init(it)
            AudioPlayProxy.instance().playSound()
        }
    }

    private fun showPag(path: String) {
        mBinding.pagView.visibility = View.VISIBLE
        mBinding.pagView.apply {
            composition = PAGFile.Load(path)
            setRepeatCount(-1)
            if (!isPlaying) {
                play()
            }
        }
    }

    //下载
    private fun loadPag(
        pagPath: String,
        loadCallback: ((path: String) -> Unit)? = null,
    ) {

        val path =
            FileUtils.getFilePath(FileUtils.getPagFile(), pagPath)
        //如果pag已经存在代表下过了直接回调
        if (File(path).exists()) {
            loadCallback?.invoke(path)
            return
        }
        mBinding.loadingLl.visibility = VISIBLE
        lifecycleScope.launch(CoroutineScopeManager.ioDispatcher) {
            val loadFileCallback = DownFileManager.loadFileCallback(
                FileUtils.getPagFile(),
                pagPath
            )
            withContext(CoroutineScopeManager.mainDispatcher) {
                val loadPath = loadFileCallback?.second?.let {
                    FileUtils.getFilePath(FileUtils.getPagFile(), it)
                }
                loadPath?.let {
                    loadCallback?.invoke(loadPath)
                }
                mBinding.loadingLl.visibility = GONE
            }
        }
    }

    override fun onDismiss() {
        super.onDismiss()
        isDismiss = true
        mPreViewEntryScreenItemView?.cancelAnimation()
        AudioPlayProxy.instance().recycle()
    }

    companion object {

        fun show(context: Context, data: UserRichCharmLevelRewardExplainVo, isViewMode: Boolean = true) {
            XPopup.Builder(context)
                .isViewMode(isViewMode)
                .isDestroyOnDismiss(true)
                .hasNavigationBar(false)
                .hasShadowBg(false)
                .asCustom(PreviewRichCharmPopup(context, data))
                .show()
        }
    }
}